package es.javamyadmin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.javamyadmin.dao.TablesDAO;
import es.javamyadmin.modelo.Tables;
import es.javamyadmin.pojo.Error;
/**
 * Servlet que inserta datos en la base de datos
 * @author Emilio Javier Castillo Gonzalez 
 * @author Hector Delgado Duran
 *
 */
public class InsertarCampo extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5454645725641164248L;

	/**
	 * Metodo que inserta un campo en la base de datos
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String user = request.getParameter("user");
		String pass = request.getParameter("pass");
		String host = request.getParameter("host");
		String port = request.getParameter("port");
		String database = request.getParameter("database");
		String tabla = request.getParameter("tabla");
		String insert = "insert into " + tabla + " (";
		String noAjax = request.getParameter("noAjax");
		String campo;
		
		if(database == null){
			database = request.getParameter("bd");
		}
		
		TablesDAO insertar = new TablesDAO();
		insertar.setPath(getServletContext().getResourceAsStream("/WEB-INF/properties/mensajes.properties"));
		Collection<Tables> lista = insertar.detalleTables(user, pass, host, port, database, tabla);
  	    Iterator<Tables> a = lista.iterator();
  	    int contador = 1;
  	    
  	    while(a.hasNext()){
  	    	Tables tablas = a.next();
  	    	if(request.getParameter("insert" + contador) != null && !request.getParameter("insert" + contador).trim().equals("")){
  	    		insert = insert + "" + tablas.getNombreColum() + ", ";
  	    	}
      	    contador++;
  	    }
  	 	
  	    insert = insert.substring(0, insert.length() - 2);
		insert = insert + ") values (";
		contador = 1;
		
		while((campo = request.getParameter("insert" + contador)) != null){
			if(!campo.trim().equals("")){
				insert = insert + "'" + campo + "', ";
			}
			contador++;
		}
		
		insert = insert.substring(0, insert.length() - 2);
		insert = insert + ")";
		
		Error error = null;
		System.out.println(insert);
		
		try {
			error = insertar.create(user, pass, host, port, database, insert);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(noAjax != null && noAjax.equals("true")){
			if(error != null){
				if(error.getError() != null){
					
					if(error.getDescripcion() != null){
						request.setAttribute("descripcion", error.getDescripcion().replace("'", "\\'"));
					}
					if(error.getError().equals("")){
						request.setAttribute("ok", "Se ha insertado correctamente");
					}else{
						request.setAttribute("error", error.getError());
					}
				}else{
					request.setAttribute("ok", "Se ha insertado correctamente");
				}
			}
			else{
				request.setAttribute("ok", "Se ha insertado correctamente");
			}
			request.getRequestDispatcher("jsp/inserccion-datos.jsp").forward(request,response);
			
		}else{
			String text = "";
			if(error != null && error.getError() != null){
				text = "{\"error\":\"" + error.getError() + "\", \"descripcion\":\"" + error.getDescripcion().replace("'", "\\'") + "\"}";
			}else{
				text = "null";
			}
			System.out.println("<insertarCampo> -post- respuesta: " + text);
			PrintWriter out = response.getWriter();
			
			try{
				out.print(text);
			}finally{
				out.close();
			}
		}
	}

}
